//
//  JKComposeTypeView.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/7/10.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit
import pop

class JKComposeTypeView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var returnButton: UIButton!
    
    @IBOutlet weak var returnButtonCenterXcons: NSLayoutConstraint!
    
    @IBOutlet weak var closeButtonCenterXcons: NSLayoutConstraint!
    // 按钮数据数组
    private let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "JKComposeViewController"],
                               ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                               ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                               ["imageName": "tabbar_compose_lbs", "title": "签到"],
                               ["imageName": "tabbar_compose_review", "title": "点评"],
                               ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                               ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                               ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                               ["imageName": "tabbar_compose_music", "title": "音乐"],
                               ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]

    
    /// 完成回调
    private var completionBlock: ((clsName: String?)->())?

    
    // MARK: - 实例化方法
    class func composeTypeView() -> JKComposeTypeView {
        // 加载 xib
        let nib = UINib(nibName: "JKComposeTypeView", bundle: nil)
        // 从 xib 加载完视图, 就会调用 awakeFromNib
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! JKComposeTypeView
        
        v.frame = UIScreen.main().bounds
        
        v.setupUI()
        
        return v
        
    }
  
    
    @IBAction func close() {
        
        removeFromSuperview()
    }
    
  
    @IBAction func clickMore() {
    
        let offset = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        
        returnButton.isHidden = false
        
        let margin = scrollView.bounds.width / 6
        
        closeButtonCenterXcons.constant += margin
        returnButtonCenterXcons.constant -= margin
        
        UIView.animate(withDuration: 0.2) {
         
            self.layoutIfNeeded()
        }
    }
    
    
    @IBAction func clickReturn() {
    
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        
        closeButtonCenterXcons.constant = 0
        returnButtonCenterXcons.constant = 0
        
        UIView.animate(withDuration: 0.2, animations: {
            self.layoutIfNeeded()
            self.returnButton.alpha = 0
        }) { _ in
            self.returnButton.isHidden = true
            self.returnButton.alpha = 1
            
        }
    }
    
    
    // 指定用 xib 就不用自定义大小了
//    override init(frame: CGRect) {
//        super.init(frame: UIScreen.main().bounds)
//        
//        backgroundColor = UIColor.cz_random()
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
   

    /// 显示当前视图
    /// OC 中的 block 如果当前方法，不能执行，通常使用属性记录，再需要的时候执行
    func show(completion: (clsName: String?)->()) {
        
        // 0> 记录闭包
        completionBlock = completion
        
        // 1> 将当前视图添加到 根视图控制器的 view
        guard let vc = UIApplication.shared().keyWindow?.rootViewController else {
            return
        }
        
        // 2> 添加视图
        vc.view.addSubview(self)
        
        
        // 3> 开始动画
        showCurrentView()
    }

//    override func awakeFromNib() {
//         setupUI()
//    }
 
    // MARk - 监听方法
    @objc private func clickButton(selectedButton: JKComposeTypeButton) {
//       print("点我了 \(btn)")
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            
            let scaleAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            let scale = (selectedButton == btn) ? 2 : 0.2
            
            scaleAnim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            
            scaleAnim.duration = 0.3
            
            btn.pop_add(scaleAnim, forKey: nil)
            
            
            // 渐变动画
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.2
            
            btn.pop_add(alphaAnim, forKey: nil)
            
            // 添加动画监听
            
            if i == 0 {
                alphaAnim.completionBlock = { _, _ in
                
                    print("完成回调展现控制器")
                    // 执行完成闭包
                    self.completionBlock?(clsName: selectedButton.clsName)

                }
            }
        }
        
    }
    
}

private extension JKComposeTypeView {

    func setupUI() {
        // 强行更新布局
        layoutIfNeeded()
        
        let rect = scrollView.bounds
        
        let width = scrollView.bounds.width
        for i in 0..<2 {
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * width, dy: 0))
            
            
            addButtons(v: v, idx: i * 6)
            
            scrollView.addSubview(v)
        }
        
        // 设置 scrollView
        scrollView.contentSize = CGSize(width: 2 * width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
     
        scrollView.isScrollEnabled = false

    }
    
    func addButtons(v: UIView, idx: Int) {
        let count = 6
        
        for i in idx..<(idx + count) {
            if i >= buttonsInfo.count {
                break
            }
            let dict = buttonsInfo[i]
            
            guard let imageName = dict["imageName"],
              title = dict["title"] else {
                continue
            }
            
            let btn = JKComposeTypeButton.composeTypeButton(imageaName: imageName, title: title)
            
            v.addSubview(btn)
            
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            
            btn.clsName = dict["clsName"]
        }
        
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * btnSize.width) / 4
        
        for (i, btn) in v.subviews.enumerated() {
            
            let y: CGFloat
            
//            let y: CGFloat = (i > 2) ? (v.bounds.height - btnSize.height) : 0
            if i < 3 {
                 y = (i > 2) ? (v.bounds.height - btnSize.height) + 10 : 0
            } else {
                 y = (i > 2) ? (v.bounds.height - btnSize.height) - 20 : 0
            }
                let col = i % 3
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            
            btn.frame = CGRect(x: x, y: y + 20, width: btnSize.width, height: btnSize.height)
        
        }
    }
}


// MARK: - 动画方法扩展
private extension JKComposeTypeView {
    
    // MARK: - 消除动画 
    // 隐藏按钮动画
    private func hideButtons() {
    
        // 1. 根据 contentOffset 判断当前显示的子视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        // 2. 遍历 v 中的所有按钮
        for (i, btn) in v.subviews.enumerated().reversed() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            
            btn.layer.pop_add(anim, forKey: nil)
            
            if i == 0 {
               
                anim.completionBlock = { _, _ in
                
                    self.removeFromSuperview()
                    
                }
            }
        }
    }
    
    // MARK: - 显示部分的动画
    // 显示当前视图
    private func showCurrentView() {
    
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        showButtons()
    }
    
    private func showButtons() {
        
        let v = scrollView.subviews[0]
        
        for (i, btn) in v.subviews.enumerated() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y + 350
            anim.toValue = btn.center.y
            
            // 弹力系数 默认是 4
            anim.springBounciness = 8
            // 弹力速度, 默认是 12
            anim.springSpeed = 8
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            btn.pop_add(anim, forKey: nil)
        }
        
        
    }

}





